import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'
import router from '..'

const whiteRoutes: string[] = ['/login', '/children/login', '/404', '/403', '/500', '/systemLogin']

function usePermissionGuard() {
  router.beforeEach(async (to) => {
    console.log(to)
    console.log(window.location.pathname.includes('/card/single'))
    if (to.path == '/login') {
      const token = localStorage.getItem('user-info')
      if (token) {
        router.push('/home/index')
      }
    } else {
      // const tokens = localStorage.getItem('user-infos')
      // if (tokens) {
      //   router.push('/children/home/monitor')
      // }
    }
    if (whiteRoutes.includes(to.path)) {
      return true
    }
    const userStore = useUserStore()
    if (userStore.isTokenExpire() && window.location.pathname.split('/')[1] != 'children') {
      return {
        path: '/login',
        query: { redirect: to.fullPath },
      }
    } else if (userStore.isTokenExpire() && window.location.pathname.split('/')[1] == 'children') {
      return {
        path: '/children/login',
        query: { redirect: to.fullPath },
      }
    }
    const permissionStore = usePermissionStore()
    const isEmptyRoute = permissionStore.isEmptyPermissionRoute()
    if (isEmptyRoute) {
      await permissionStore.initPermissionRoute()
      return { ...to, replace: true }
    }
    return true
  })
}

export default usePermissionGuard
